using UnityEngine;
using System.Collections;

public class PlayerControl : MonoBehaviour {
	
	public float currentOffset = 0;
	public GameObject spritePlane;
	public GameObject cameraObject;
	public CharacterController cc;
	public float moveSpeed;
	public float spriteWait;
	public float slowSpriteSpeed;
	public float fastSpriteSpeed;
	public float defaultSpriteSpeed;
	public float relativeX;
	public float verticalSpeed;
	public Vector3 vectorMove;
	public bool canJump;
	public int life = 3; 
	
	// Use this for initialization
	void Start () {
		StartCoroutine(newOffset());
		cc = GetComponent<CharacterController>();
	}
	
	// Update is called once per frame
	void Update () {
		
		if(cc.isGrounded)
		{
			canJump = true;
			verticalSpeed = 0;	
			if(Input.GetKeyDown(KeyCode.UpArrow))
			{
				verticalSpeed = 12f;
			}
			
		}
		else
		{
			if(Input.GetKeyDown(KeyCode.UpArrow) && canJump)
			{
				verticalSpeed = 12f;
				canJump = false;
			}
		}
		verticalSpeed -= 40 * Time.deltaTime;
		
		relativeX = transform.position.x - cameraObject.transform.position.x;
		
		vectorMove = new Vector3(moveSpeed * 1.4f, verticalSpeed, 0);
		
		cc.Move(vectorMove * Time.deltaTime);
		
		if(Input.GetKey(KeyCode.RightArrow) && (relativeX <= 4.5f))
		{
			spriteWait = fastSpriteSpeed;
			cc.Move(Vector3.right * Time.deltaTime * moveSpeed);
		}
		
		else if(Input.GetKey(KeyCode.LeftArrow) && (relativeX >= -4.5f))
		{
			spriteWait = slowSpriteSpeed;
			cc.Move(-Vector3.right * Time.deltaTime * moveSpeed);
		}
		
		else
		{
				spriteWait = defaultSpriteSpeed;
		}
		
		
	
	
	}
	
	void OnControllerColliderHit(ControllerColliderHit hit)
	{
		Rigidbody body = hit.collider.attachedRigidbody;
		if(hit.moveDirection.x > 0.1)
			return;
		if(hit.moveDirection.y > 0.1)
			return;
		
	}
	
	
	
	IEnumerator newOffset()
	{
		yield return new WaitForSeconds(spriteWait);


		currentOffset += 0.08333334f;
			
		if(currentOffset > 1)
			currentOffset = 0;
		
		
		spritePlane.renderer.material.mainTextureOffset = new Vector2(currentOffset, 0);
		
		StartCoroutine(newOffset());
		

	}
	
	void OnTriggerEnter(Collider other)
	{
		if(other.tag == "Enemy")
		{
			Destroy(other.gameObject);
		}
	}
	

}
